﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WC.BL.BCC;
using WC.BL.BE;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;

namespace WC.UI.WebApp
{
    public partial class CuentaCorriente : System.Web.UI.Page
    {
        private decimal _subTotalML = 0m; 
        private decimal _subTotalMD = 0m;
        private decimal _subTotalMDUS = 0m;
        private decimal _totalML = 0m; private decimal _totalMD = 0m; private decimal _totalMDUS = 0m;
        private UsuarioBE _lvObjUsuarioBE;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    this.lblExportar.Visible = false;
                    this.ibtnExcel.Visible = false;
                    txtFechaAbiertas.Text = DateTime.Now.Date.ToShortDateString();
                }
                catch { }
            }
        }

        protected void ibtnBuscar_Click(object sender, ImageClickEventArgs e)
        {
            this.llenaDatosCtaCte();
        }
        
        protected void dgPartidas_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Moneda")) == "PEN")
                {
                    this._subTotalMD += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Importe"));
                }
                else if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Moneda")) == "USD")
                {
                    this._subTotalMDUS += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Importe"));
                }
                this._subTotalML += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ImporteMonLocal"));
               
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                try
                {
                    //e.Row.Cells[10].Text = string.Format("{0:n}", this._subTotalML);
                    //e.Row.Cells[10].HorizontalAlign = HorizontalAlign.Right;
                    //e.Row.Cells[10].VerticalAlign = VerticalAlign.Top;

                    //e.Row.Cells[9].Text = string.Format("{0:n}", this._subTotalMD);
                    //e.Row.Cells[9].HorizontalAlign = HorizontalAlign.Right;
                    //e.Row.Cells[9].VerticalAlign = VerticalAlign.Top;

                    //e.Row.VerticalAlign = VerticalAlign.Top;

                    this._totalMD += this._subTotalMD;
                    this._subTotalMD = 0m;
                    this._totalML += this._subTotalML;
                    this._subTotalML = 0m;

                    this._totalMDUS += this._subTotalMDUS;
                    this._subTotalMDUS = 0m;

                    Literal LabelPEN = (Literal)e.Row.FindControl("LabelPEN");
                    LabelPEN.Text = string.Format("{0:0,0.00}", this._totalMD);

                    Literal LabelUSD = (Literal)e.Row.FindControl("LabelUSD");
                    LabelUSD.Text = string.Format("{0:0,0.00}", this._totalMDUS);

                    Literal LabelML2 = (Literal)e.Row.FindControl("LabelML2");
                    LabelML2.Text = string.Format("{0:0,0.00}", this._totalML);                    
                }
                catch 
                {
                    
                }
                
            }
        }

        protected void dlDetalle_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label lblImporteTotal = (Label)e.Item.FindControl("lblImporteTotal");
                lblImporteTotal.Text = string.Format("{0:0,0.00}", this._totalML);
            }
        }

        protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)
        {

            if (dgPartidas.Rows.Count > 0)
            {
                exportarExcel("ctacte_" + txtCodCuentaDeudor.Text + ".xls", ((List<CtaCteBE>)Session["lstPartidas"]));
            }
            else
            {
                Session["Mensaje"] = "No existe información para exportar.";
            }
        }

        #region web service
        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] buscaClientes(string prefixText, int count)
        {
            string[] retVal;
            //List<GenericBE> lstClientes = UsuarioBC.read(false);
            List<ClienteBE> lstClientes = ClienteBC.find(string.Empty, prefixText, string.Empty);
            List<string> lst = new List<string>();
            int total = lstClientes.Count < count ? lstClientes.Count : count;
            for (int i = 0; i < total; i++)
            {
                string item = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(lstClientes[i].Nombre, lstClientes[i].Codigo);
                lst.Add(item);
            }
            retVal = lst.ToArray();
            return retVal;
        }

        #endregion

        #region metodos internos
        private void llenaDatosCtaCte()
        {
            this.lblExportar.Visible = false;
            this.ibtnExcel.Visible = false;
            try
            {
                string codCliente = txtCodCuentaDeudor.Text.Trim();
                string fecha = txtFechaAbiertas.Text.Trim(); DateTime pFecha = DateTime.Today;
                if (!string.IsNullOrEmpty(codCliente))
                {
                    if (!string.IsNullOrEmpty(fecha))
                    {
                        try
                        {
                            pFecha = Convert.ToDateTime(fecha);
                        }
                        catch (Exception ex) { Session["Mensaje"] = "Fecha ingresada es inválida.\n" + ex.Message; }
                    }
                    List<CtaCteBE> lstPartidas = CtaCteBC.read(codCliente, "1000", pFecha);
                    dgPartidas.DataSource = lstPartidas;
                    dgPartidas.DataBind();
                    Session["lstPartidas"] = lstPartidas;

                    if (lstPartidas != null)
                        if (lstPartidas.Count > 0)
                        {
                            this.lblExportar.Visible = true;
                            this.ibtnExcel.Visible = true;
                        }

                    if (lstPartidas.Count == 0) Session["Mensaje"] = "No se encontró coincidencias.";
                    //var xys = from x in lstPartidas
                    //          orderby x.ClaseDoc, x.NumDocumento, x.CodReferencia
                    //          group x by new { x.ClaseDoc };

                    //List<GrpCtaCteBE> lstPartidasGrp = new List<GrpCtaCteBE>();
                    //foreach (var xy in xys)
                    //{
                    //    GrpCtaCteBE objPartidasGrp = new GrpCtaCteBE();

                    //    objPartidasGrp.ClaseDoc = xy.Key.ClaseDoc;
                    //    objPartidasGrp.ImporteTotalML = xy.Sum(item => item.ImporteMonLocal);

                    //    lstPartidasGrp.Add(objPartidasGrp);
                    //}

                    ////decimal impTotal = 0m;
                    //foreach (GrpCtaCteBE item in lstPartidasGrp)
                    //{
                    //    item.Partidas = lstPartidas.FindAll(X => X.ClaseDoc == item.ClaseDoc);
                    //}

                    //dlDetalle.DataSource = lstPartidasGrp;
                    //dlDetalle.DataBind();
                    //Session["lstPartidas"] = lstPartidasGrp;
                }
            }
            catch (Exception ex)
            {
                Session["Mensaje"] = ex.Message;
            }
            finally
            {
               ((Main)Master).muestraMensajes();
            }
        }
        
        private void exportarExcel(string pNArchivo, List<CtaCteBE> plst)
        {
            DataTable dt = new DataTable();
            List<CtaCteBE> lst = plst;
            dt.Columns.Add("Cuenta");
            dt.Columns.Add("Cliente");
            dt.Columns.Add("Fecha doc.");
            dt.Columns.Add("Venc. neto");
            dt.Columns.Add("N° doc.");
            dt.Columns.Add("CPag");
            dt.Columns.Add("Demora");
            dt.Columns.Add("Cla");
            dt.Columns.Add("Referencia");
            dt.Columns.Add("Mon");
            dt.Columns.Add("Importe en MD");
            dt.Columns.Add("Importe en ML2");
            dt.Columns.Add("Texto");

            if (lst != null)
                if (lst.Count > 0)
                {
                    string cd = lst[0].ClaseDoc;
                    decimal suma = 0m; decimal sumaMD = 0m;
                    foreach (CtaCteBE cta in lst)
                    {
                        DataRow r = dt.NewRow();
                        r["Cuenta"] = cta.CodCliente;
                        r["Cliente"] = cta.NomCliente;
                        r["Fecha doc."] = cta.FechaDoc.ToString("dd/MM/yyyy");// ToShortDateString();
                        r["Venc. neto"] = cta.FecVenc.ToString("dd/MM/yyyy"); //.ToShortDateString();
                        r["N° doc."] = cta.NumDocumento;
                        r["CPag"] = cta.CondPago;
                        r["Demora"] = cta.Demora.ToString();
                        r["Cla"] = cta.ClaseDoc;
                        r["Referencia"] = cta.CodReferencia;
                        r["Mon"] = cta.Moneda;
                        r["Importe en MD"] = cta.Importe.ToString("#,#.##", CultureInfo.InvariantCulture);
                        r["Importe en ML2"] = cta.ImporteMonLocal.ToString("#,#.##", CultureInfo.InvariantCulture);
                        r["Texto"] = cta.Texto;
                        dt.Rows.Add(r);
                        suma += cta.ImporteMonLocal;
                        sumaMD += cta.Importe;
                    }
                    if (dt.Rows.Count > 0)
                    {
                        DataRow r = dt.NewRow();
                        r["Cuenta"] = string.Empty;
                        r["Cliente"] = string.Empty;
                        r["Fecha doc."] = string.Empty;
                        r["Venc. neto"] = string.Empty;
                        r["N° doc."] = string.Empty;
                        r["CPag"] = string.Empty;
                        r["Demora"] = string.Empty;
                        r["Cla"] = string.Empty;
                        r["Referencia"] = string.Empty;
                        r["Mon"] = string.Empty;
                        r["Importe en MD"] = sumaMD.ToString("#,#.##", CultureInfo.InvariantCulture);
                        r["Importe en ML2"] = suma.ToString("#,#.##", CultureInfo.InvariantCulture);
                        r["Texto"] = string.Empty;
                        dt.Rows.Add(r);
                    }
                    DataGrid dg = new DataGrid();
                    dg.DataSource = dt;//((List<CtaCteBE>)Session["lstPartidasGrp"]);
                    dg.DataBind();
                    dg.AutoGenerateColumns = true;

                    string filename = pNArchivo;
                    Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.ContentEncoding = Encoding.Unicode;
                    Response.BinaryWrite(Encoding.Unicode.GetPreamble());
                    Response.Charset = "";
                    this.EnableViewState = false;
                    StringWriter tw = new StringWriter();
                    HtmlTextWriter hw = new HtmlTextWriter(tw);
                    dg.RenderControl(hw);


                    Response.AppendHeader("content-disposition", "attachment;filename=" + filename);
                    Response.Write(tw.ToString());
                    Response.End();
                }
        }

        #endregion

        protected void dgPartidas_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                //TableRow tr = new TableRow();
                //TableCell cell1 = new TableCell();
                //cell1.Text = this._subTotalMD.ToString();

                //TableCell cell2 = new TableCell();
                //cell2.Text = this._subTotalMDUS.ToString();

                //e.Row.Cells.Clear();
                //e.Row.Cells.Add(cell1);
                //e.Row.Cells.Add(cell2);
            }
        }

    }
}
